import { time2str } from '@/widgets'
import { registerEntityType, requestModel } from '../base'
import { initFlightPlanIndex } from './fpl-index'
import { initFlightPlanMapItems } from './map-item'
import type { FlightPlan } from './types'
import { registerEntityTable } from '../table'
import { getFlightPlanInfoById, setupFlightPlanInfos } from './fpl-info'
import { registerAppMenu } from '@/app'
import {
  selectAndShowAircraftFlightPlanTable,
  selectAndShowAirportArrivalFlightPlanTable,
  selectAndShowAirportDepartureFlightPlanTable
} from './util'
import FlightPlanFilterVue from './FlightPlanFilter.vue'

export { flightPlanByAircraft, flightPlanByRouting } from './fpl-index'
export { flightPlanMapItem } from './map-item'
export {
  showAircraftFlightPlanTable,
  showAirportDepartureFlightPlanTable,
  showAirportArrivalFlightPlanTable,
  selectAndShowAircraftFlightPlanTable,
  selectAndShowAirportDepartureFlightPlanTable,
  selectAndShowAirportArrivalFlightPlanTable
} from './util'

function setupFlightPlanTable() {
  registerEntityTable<FlightPlan>({
    type: 'FlightPlan',
    columns: [
      {
        name: 'id',
        cell: (e) => e.id,
        width: 100
      },
      {
        name: '飞机',
        cell: (e) => e.aircraft,
        width: 100
      },
      {
        name: '起飞机场',
        cell: (e) => getFlightPlanInfoById(e.id).depApt || '',
        width: 100
      },
      {
        name: '落地机场',
        cell: (e) => getFlightPlanInfoById(e.id).arrApt || '',
        width: 100
      },
      {
        name: '飞行路线',
        cell: (e) => e.routing,
        width: 100
      },
      {
        name: '开始时间',
        cell: (e) => time2str(e.startTime),
        width: 100
      },
      {
        name: '离港点',
        cell: (e) => getFlightPlanInfoById(e.id).depFix || '',
        width: 100
      },
      {
        name: '进港点',
        cell: (e) => getFlightPlanInfoById(e.id).arrFix || '',
        width: 100
      }
    ],
    filter: FlightPlanFilterVue
  })
}

export async function setupFlightPlan() {
  const data = (await requestModel('FlightPlan')) as FlightPlan[]
  registerEntityType<FlightPlan>({
    type: 'FlightPlan',
    typeName: '飞行计划',
    data
  })
  setupFlightPlanInfos(data)
  setupFlightPlanTable()
  initFlightPlanIndex(data)
  initFlightPlanMapItems()

  registerAppMenu({
    path: '模型/{mas-icon-FlightPlan}查看飞机对应航班',
    onClick: selectAndShowAircraftFlightPlanTable
  })
  registerAppMenu({
    path: '模型/apt:{mas-icon-FlightPlan}查看机场离港航班',
    onClick: selectAndShowAirportDepartureFlightPlanTable
  })
  registerAppMenu({
    path: '模型/apt:{mas-icon-FlightPlan}查看机场进港航班',
    onClick: selectAndShowAirportArrivalFlightPlanTable
  })
}
